package org.squarecap.apps.eventcompanion.web;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.SecureRandom;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.squarecap.apps.eventcompanion.domain.*;
import org.squarecap.apps.eventcompanion.util.EmailSender;

@Controller
public class LoginController {
	
	@Autowired
	EmailSender emailSender;
	@Autowired
	private SecureRandom secureRandom;
	
    @RequestMapping(value = "/resetPassword", method = RequestMethod.GET, produces = "text/html")
    public String resetPassword(@RequestParam(value = "j_username", required = false) String email, Model uiModel) {
    	Usuario user = null;
    	try {
    		user = Usuario.findUsuariosByEmail(email);
    		if (user instanceof Admin){
    			user = null;
    		}
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
    	if (user != null){
    		secureRandom = new SecureRandom();
    		String newPass = new BigInteger(130, secureRandom).toString(32);
    		user.setClave(DigestUtils.sha256Hex(newPass));
    		System.out.println("Sha usuario" + user.getClave());
    		user.merge();
    		StringBuilder strBuilder = new StringBuilder();
    		strBuilder.append("Estimado usuario: ");
    		strBuilder.append("\n");
    		strBuilder.append("Su nueva contraseña es: ");
    		strBuilder.append(newPass);
    		
    		emailSender.sendEmail(email, "Reseteo de clave Event Companion", strBuilder.toString());
        	uiModel.addAttribute("success", "true");
    	} else {
    		uiModel.addAttribute("success", "false");
    	}
		return "resetPassword";
    }
	
	@RequestMapping(value = "/showUser", method = RequestMethod.GET, produces = "text/html")
    public String updateUsername(@RequestParam(value = "username", required = false) String username, Model uiModel, HttpServletRequest httpServletRequest) {
    	Usuario loggedUsuario = null;
    	try {
			loggedUsuario = Usuario.findUsuariosByEmail(username);
		} catch (Exception e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
		}
		if (loggedUsuario instanceof AdminCongreso){
		    return "redirect:/admincongresoes/" + encodeUrlPathSegment(((AdminCongreso) loggedUsuario).getId().toString(), httpServletRequest);
		} else if (loggedUsuario instanceof Participante){
		    return "redirect:/participantes/" + encodeUrlPathSegment(((Participante) loggedUsuario).getId().toString(), httpServletRequest);
		}
		return "redirect:/congresoes";
    }
    
	String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }
	
}
